<template>
  <div class="article-detail-container">
    <Navbar />

    <el-container class="content-container">
      <el-aside width="280px">
        <el-card class="sidebar-card">
          <div class="author-info">
            <h3>作者信息</h3>
            <el-avatar :size="100" :src="authorAvatar" class="author-avatar" />
            <h4 class="author-name">{{ article.author }}</h4>
            <p class="author-desc">简介：这是一位优秀的作者</p>
          </div>

          <div class="related-articles" style="margin-top: 30px;">
            <h3>相关文章</h3>
            <el-list class="related-list" :border="true">
              <el-list-item v-for="related in relatedArticles" :key="related.id" @click="goToRelated(related.id)">
                <div class="related-title">{{ related.title }}</div>
              </el-list-item>
            </el-list>
          </div>
        </el-card>
      </el-aside>

      <el-container>
        <el-header class="content-header">
          <h1>文章详情</h1>
        </el-header>

        <el-main class="article-content">
          <div v-if="article" class="detail-content">
            <h2 class="article-title">{{ article.title }}</h2>

            <div class="article-meta">
              <span class="article-category" :class="getCategoryClass(article.category)">{{ article.category || '未分类'
                }}</span>
              <span class="article-date">{{ formatDate(article.createdAt) }}</span>
              <span class="article-views">阅读: {{ article.views || 0 }}</span>
            </div>

            <div v-if="article.image" class="article-image-container">
              <img :src="article.image" alt="文章图片" class="article-detail-image" />
            </div>

            <div class="article-body" v-html="article.content"></div>

            <div class="article-tags">
              <span v-for="tag in article.tags || []" :key="tag" class="tag">{{ tag }}</span>
            </div>

            <div class="article-actions">
              <el-button type="primary" @click="likeArticle">
                <template v-if="isLiked">
                  <el-icon>
                    <HeartFilled />
                  </el-icon>
                </template>
                <template v-else>
                  <el-icon>
                    <Heart />
                  </el-icon>
                </template>
                <span>({{ article.likes || 0 }})</span>
                <span v-if="isLiked">已点赞</span>
                <span v-else>点赞</span>
              </el-button>
              <el-button @click="shareArticle">
                <el-icon>
                  <Share />
                </el-icon>分享
              </el-button>
            </div>

            <CommentForm :articleId="article.id" />

            <div class="comment-section">
              <h3 class="comment-title">评论区 ({{ commentCount }})</h3>
              <CommentList :articleId="article.id" />
            </div>
          </div>

          <el-empty v-else description="文章加载中..."></el-empty>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElIcon } from 'element-plus';
import Heart from '@element-plus/icons-vue/Heart';
import HeartFilled from '@element-plus/icons-vue/HeartFilled';
import Share from '@element-plus/icons-vue/Share';
import { useUserStore } from '@/stores/userStore'
import { useArticleStore } from '@/stores/articleStore'
import { useCommentStore } from '@/stores/commentStore'
import Navbar from '@/components/Navbar.vue'
import CommentForm from '@/components/CommentForm.vue'
import CommentList from '@/components/CommentList.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const articleStore = useArticleStore()
const commentStore = useCommentStore()

// 文章ID
const articleId = route.params.id as string

// 数据状态
const article = ref(null)
const relatedArticles = ref([] as any[])
const isLiked = ref(false)
const commentCount = ref(0)

// 生命周期钩子
onMounted(async () => {
  await fetchArticleDetail()
  fetchRelatedArticles()
  fetchComments()
})

// 监听文章ID变化
watch(
  () => route.params.id,
  async (newId) => {
    if (newId) {
      articleId = newId
      await fetchArticleDetail()
      fetchRelatedArticles()
      fetchComments()
    }
  }
)

// 获取文章详情
const fetchArticleDetail = async () => {
  try {
    const data = await articleStore.fetchArticle(articleId)
    article.value = data

    // 检查是否已点赞
    isLiked.value = data.likes?.includes(userStore.user?.id || '') || false
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '获取文章详情失败')
    if (error.response?.status === 404) {
      router.push('/')
    }
  }
}

// 获取相关文章
const fetchRelatedArticles = () => {
  if (!article.value) return

  // 这里简化处理，实际项目中应根据分类或标签获取相关文章
  relatedArticles.value = articleStore.articles
    .filter(item => item.id !== articleId)
    .slice(0, 5)
}

// 获取评论
const fetchComments = async () => {
  try {
    const comments = await commentStore.fetchArticleComments(articleId)
    commentCount.value = comments.length
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '获取评论失败')
  }
}

// 格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
}

// 获取分类样式
const getCategoryClass = (category: string | undefined) => {
  const categoryMap: Record<string, string> = {
    '国内新闻': 'category-domestic',
    '国际新闻': 'category-international',
    '科技新闻': 'category-technology',
    '娱乐新闻': 'category-entertainment',
    '体育新闻': 'category-sports'
  }
  return categoryMap[category || ''] || ''
}

// 计算作者头像
const authorAvatar = computed(() => {
  if (!article.value) return 'https://picsum.photos/100/100?random=user'

  const initials = article.value.author?.charAt(0)?.toUpperCase() || 'U'
  return `https://picsum.photos/100/100?random=${initials}`
})

// 点赞文章
const likeArticle = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  try {
    if (isLiked.value) {
      // 取消点赞
      await articleStore.unlikeArticle(articleId)
      isLiked.value = false
      article.value!.likes = article.value!.likes?.filter(id => id !== userStore.user?.id)
    } else {
      // 点赞
      await articleStore.likeArticle(articleId)
      isLiked.value = true
      article.value!.likes = [...(article.value!.likes || []), userStore.user?.id]
    }

    ElMessage.success(isLiked.value ? '点赞成功' : '已取消点赞')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  }
}

// 分享文章
const shareArticle = () => {
  if (!article.value) return

  ElMessageBox.alert(`分享文章: ${article.value.title}\n链接: ${window.location.href}`, '分享文章')
}

// 前往相关文章
const goToRelated = (id: string) => {
  router.push(`/article/${id}`)
}
</script>

<style scoped>
.article-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-container {
  height: calc(100vh - 60px);
}

.content-header {
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 0 20px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.detail-content {
  background-color: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.article-title {
  font-size: 28px;
  font-weight: 700;
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.article-meta {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  color: #909399;
  font-size: 14px;
}

.article-meta .article-category {
  margin-right: 15px;
}

.article-image-container {
  text-align: center;
  margin: 30px 0;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.article-detail-image {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
}

.article-body {
  line-height: 1.8;
  font-size: 16px;
  color: #303133;
  margin-bottom: 30px;
  text-align: justify;
}

.article-body p {
  margin-bottom: 16px;
}

.article-body img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 15px 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.article-tags {
  margin: 20px 0;
}

.tag {
  display: inline-block;
  padding: 4px 12px;
  background-color: #f0f2f5;
  color: #606266;
  border-radius: 4px;
  margin-right: 10px;
  margin-bottom: 10px;
  font-size: 14px;
}

.article-actions {
  display: flex;
  justify-content: center;
  margin: 30px 0;
}

.article-actions .el-button {
  margin: 0 10px;
}

.comment-section {
  margin-top: 50px;
  padding-top: 30px;
  border-top: 1px solid #ebeef5;
}

.comment-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #303133;
}

.sidebar-card {
  height: 100%;
  border-radius: 0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
  padding: 20px;
}

.author-info {
  text-align: center;
  margin-bottom: 20px;
}

.author-avatar {
  margin-bottom: 15px;
}

.author-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #303133;
}

.author-desc {
  font-size: 14px;
  color: #909399;
  margin-bottom: 0;
}

.related-articles {
  margin-top: 20px;
}

.related-list {
  padding: 0;
}

.related-title {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  transition: color 0.3s ease;
}

.related-title:hover {
  color: #409EFF;
}
</style>